package zozopo.search;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.Date;


import org.apache.lucene.store.FSDirectory;


import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.wltea.analyzer.lucene.IKAnalyzer;

import zozopo.comm.HTMLDisplay;
import zozopo.comm.Validate;
import zozopo.database.BusiDatabaseManager;
import zozopo.database.DatabaseManager;
import zozopo.manual.operations.ReleaseTB;
import zozopo.operations.business.StoreTB;
import zozopo.operations.comm.DictionaryOS;

/**  
 * @author ht  
 * 索引生成  
 *  
 */  
public class Indexer {   
	
	
	public Indexer(Connection conn){
		//super(conn);
	}
	
	public Indexer(){
		/*this.databaseConnection = new BusiDatabaseManager();
		this.conn = databaseConnection.getConnection();*/
	}
   private static String INDEX_DIR = "search/index";//索引存放目录   
   //private static String DATA_DIR = "D:\\test\\small\\";//小文件存放的目录   
       
  public void initIndex(ResultSet resultSet) throws IOException {   
    
    long start = new Date().getTime();   
    int numIndexed = index(new File(INDEX_DIR));//调用index方法   
    long end = new Date().getTime();   
    System.out.println("Indexing " + numIndexed + " files took " + (end - start) + " milliseconds");   //*/
  }   
  


	
	 /**索引dataDir下的.txt文件，并储存在indexDir下，返回索引的文件数量  
	 * @param indexDir  
	 * @param dataDir  
	 * @return int   
	 * @throws IOException  
	 */  
	public int index(File indexDir) throws IOException {   
		
		Analyzer luceneAnalyzer = new IKAnalyzer();
		//建立内存索引对象   
	    IndexWriter iwriter = new IndexWriter(FSDirectory.open(indexDir), luceneAnalyzer, true , IndexWriter.MaxFieldLength.LIMITED);   
	       
	    indexDirectory(iwriter);   
	    int numIndexed = iwriter.numDocs();   
	    iwriter.optimize();   
	    iwriter.close();   
	    return numIndexed;   
	  }  

	
	
	/**对单个Release表进行索引  
	 * @param writer  
	 * @param f  
	 * @throws IOException 
	 * @throws CorruptIndexException 
	 * @throws IOException  
	 */  
	private void indexSearcherBean(IndexWriter writer,SearcherBean searcherBean) throws CorruptIndexException, IOException{
		Document doc = new Document();  
		//doc.add(new Field("subject",release.getRelease_subject(),Field.Store.YES,Field.Index.ANALYZED));//有变化的地方   
       // String content = Validate.htmlFilter(searcherBean.getContent());
	
		doc.add(new Field("content",searcherBean.getContent()+"",Field.Store.YES, Field.Index.ANALYZED));//有变化的地方  
		doc.add(new Field("id",searcherBean.getId()+"",Field.Store.YES,Field.Index.ANALYZED));//有变化的地方   
		doc.add(new Field("kind",searcherBean.getKind()+"",Field.Store.YES, Field.Index.ANALYZED));//有变化的地方   
		
		doc.add(new Field("title",searcherBean.getTitle()+"",Field.Store.YES,Field.Index.NOT_ANALYZED));//有变化的地方   
	    doc.add(new Field("htmlcode",searcherBean.getHtmlcode()+"",Field.Store.YES,Field.Index.NOT_ANALYZED));//有变化的地方   
	    doc.add(new Field("introduction",searcherBean.getIntroduction()+"",Field.Store.YES,Field.Index.NOT_ANALYZED));//有变化的地方   
	    doc.add(new Field("image",searcherBean.getImage()+"",Field.Store.YES,Field.Index.NOT_ANALYZED));//有变化的地方   
	    doc.add(new Field("date",searcherBean.getDate()+"",Field.Store.YES,Field.Index.NOT_ANALYZED));//有变化的地方   
	    doc.add(new Field("url",searcherBean.getUrl()+"",Field.Store.YES, Field.Index.NOT_ANALYZED));//有变化的地方   
	   // System.out.println(strbuff.toString());//*/
	    writer.addDocument(doc); 
	     
	}
	
	/**循环遍历目录下的所有release并进行索引  
	 * @param writer  
	 * @param resultSet  
	 */  
	private void indexDirectory(IndexWriter writer) {
		
		indexRelease(writer);
		
		indexStore(writer);
		
		
	}
	
	public void indexRelease(IndexWriter writer){
		DatabaseManager databaseConnection = null;
		Connection conn = null;
		
		databaseConnection = new BusiDatabaseManager();
		conn = databaseConnection.getConnection();
		
		//index release_subject
		String sql = "select * from "+ReleaseTB.TABLE_NAME 
		 + " order by "+ReleaseTB.RELEASE_DATE+" desc ";
		
		
		DictionaryOS dictionaryOS = new DictionaryOS(conn);
		
		
		
		/*
		ReleaseOS releaseOS = new ReleaseOS();
		List<ReleaseTB> releaseList = releaseOS.saerchAllRelease();
		for(ReleaseTB release:releaseList){
			SearcherBean searcherBean = new SearcherBean();
			
			String content = Validate.htmlFilter(release.getRelease_context());
			String introduction = "";
			if(content.length() >=200 ){
				introduction = content.substring(0, 200) + "...";
			}
			
			StringBuffer contentBuff = new StringBuffer();
			contentBuff.append(content);
			contentBuff.append(release.getRelease_subject());
			contentBuff.append(release.getRelease_brand());
			contentBuff.append(release.getRelease_secondbrand());
			contentBuff.append(release.getRelease_kindvalue());
			contentBuff.append(release.getRelease_labledicvalue());
			
			searcherBean.setId(release.getRelease_id());
			searcherBean.setContent(contentBuff.toString());
			searcherBean.setIntroduction(introduction);
			searcherBean.setImage(release.getRelease_image());
			searcherBean.setDate(release.getRelease_date());
			searcherBean.setUrl("view.action?id="+release.getRelease_id());
			searcherBean.setTitle(release.getRelease_subject());
			searcherBean.setHtmlcode("");
			searcherBean.setKind("");
			
			try {
				indexSearcherBean(writer,searcherBean);
			} catch (CorruptIndexException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		releaseOS.releaseConnection();//*/
		
		
		ResultSet resultSet = databaseConnection.executeQuery(conn, sql);
		if(resultSet != null){
			try {
			
				while(resultSet.next()){
					ReleaseTB release = new ReleaseTB();
					release.setRelease_id(resultSet.getString(ReleaseTB.RELEASE_ID));
					release.setRelease_brand(resultSet.getString(ReleaseTB.RELEASE_BRAND));
					release.setRelease_brand(resultSet.getString(ReleaseTB.RELEASE_SECONDBRAND));
					release.setRelease_context(resultSet.getString(ReleaseTB.RELEASE_CONTEXT)+"");
				
					release.setRelease_date(resultSet.getString(ReleaseTB.RELEASE_DATE));
					release.setRelease_des(resultSet.getString(ReleaseTB.RELEASE_DES));
					release.setRelease_key(resultSet.getString(ReleaseTB.RELEASE_KEY));
					release.setRelease_lable(resultSet.getString(ReleaseTB.RELEASE_LABLE));
					
					release.setRelease_from(resultSet.getString(ReleaseTB.RELEASE_FROM));
					release.setRelease_kind(resultSet.getString(ReleaseTB.RELEASE_KIND));
					
					release.setRelease_md_date(resultSet.getString(ReleaseTB.RELEASE_MD_DATE));
					release.setRelease_subject(resultSet.getString(ReleaseTB.RELEASE_SUBJECT));
					release.setRelease_url(resultSet.getString(ReleaseTB.RELEASE_URL));
					release.setRelease_ip(resultSet.getString(ReleaseTB.RELEASE_IP));
					release.setRelease_useremail(resultSet.getString(ReleaseTB.RELEASE_USERMEAIL));
					release.setRelease_state(resultSet.getString(ReleaseTB.RELEASE_STATE));
					release.setRelease_image(resultSet.getString(ReleaseTB.RELEASE_IMAGE));
					
					release.setRelease_bear(resultSet.getInt(ReleaseTB.RELEASE_BEAR));
					release.setRelease_replys(resultSet.getInt(ReleaseTB.RELEASE_REPLYS));
					release.setRelease_views(resultSet.getInt(ReleaseTB.RELEASE_VIEWS));
					
					
					release.setRelease_labledicvalue(dictionaryOS.getDictValue(release.getRelease_lable()));//为了显示
					release.setRelease_kindvalue(dictionaryOS.getDictValue(release.getRelease_kind()));//为了显示
					
					
					SearcherBean searcherBean = new SearcherBean();
					
					String content = Validate.htmlFilter(release.getRelease_context());
					String introduction = "";
					if(content.length() >=200 ){
						introduction = content.substring(0, 200) + "...";
					}else{
						introduction = content;
					}
					
					StringBuffer contentBuff = new StringBuffer();
					contentBuff.append(content);
					contentBuff.append(release.getRelease_subject());
					contentBuff.append(release.getRelease_brand());
					contentBuff.append(release.getRelease_secondbrand());
					contentBuff.append(release.getRelease_kindvalue());
					contentBuff.append(release.getRelease_labledicvalue());
					
					searcherBean.setId(release.getRelease_id());
					searcherBean.setContent(contentBuff.toString());
					searcherBean.setIntroduction(introduction);
					searcherBean.setImage(release.getRelease_image());
					searcherBean.setDate(release.getRelease_date());
					searcherBean.setUrl("view.action?id="+release.getRelease_id());
					searcherBean.setTitle(release.getRelease_subject());
					searcherBean.setHtmlcode("");
					searcherBean.setKind("");
					
					indexSearcherBean(writer,searcherBean);
					//indexSubject(writer,release);
				}
				resultSet.close();
				
				
				
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (CorruptIndexException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			
					
					
		}//*/
	}
	
	public void indexStore(IndexWriter writer){
		//index store
		
		DatabaseManager databaseConnection = null;
		Connection conn = null;
		
		databaseConnection = new BusiDatabaseManager();
		conn = databaseConnection.getConnection();
		
		DictionaryOS dictionaryOS = new DictionaryOS(conn);
		
		String sqlForStore = "select * from "+StoreTB.TABLE_NAME;
		
		ResultSet storeResultSet = databaseConnection.executeQuery(conn, sqlForStore);
		
		if(storeResultSet != null){
			
			
				try {
					while(storeResultSet.next()){
						StoreTB store = new StoreTB();
						
						store.setId_store(storeResultSet.getInt(StoreTB.ID_STORE));
						store.setContent_store(storeResultSet.getString(StoreTB.CONTENT_STORE));
						
						store.setName_store(storeResultSet.getString(StoreTB.NAME_STORE));
						store.setCnbrand_store(storeResultSet.getString(StoreTB.CNBRAND_STORE));
						store.setCnspell_store(storeResultSet.getString(StoreTB.CNSPELL_STORE));
						store.setEnbrand_store(storeResultSet.getString(StoreTB.CONTENT_STORE));
						store.setStar_store(storeResultSet.getInt(StoreTB.STAR_STORE));
						
						store.setKind_store(storeResultSet.getString(StoreTB.KIND_STORE));
						store.setLable_store(storeResultSet.getString(StoreTB.LABLE_STORE));
						
						store.setKindvalue(dictionaryOS.getDictValue(store.getKind_store()));
						store.setLablevalue(dictionaryOS.getDictValue(store.getLable_store()));
						
						
						SearcherBean searcherBean = new SearcherBean();
						
						String content = Validate.htmlFilter(store.getContent_store());
						String introduction = "";
						if(content.length() >=200 ){
							introduction = content.substring(0, 200) + "...";
						}else{
							introduction = content;
						}
						
						StringBuffer contentBuff = new StringBuffer();
						contentBuff.append(store.getCnbrand_store()+"网店");
						contentBuff.append(store.getEnbrand_store()+"网店");
						
						contentBuff.append(content);
						contentBuff.append(store.getName_store());
						contentBuff.append(store.getKindvalue());
						contentBuff.append(store.getLablevalue());
						contentBuff.append(store.getCnbrand_store());
						contentBuff.append(store.getCnspell_store());
						contentBuff.append(store.getEnbrand_store());
						
						StringBuffer htmlBuff = new StringBuffer();
						
						htmlBuff.append("<br/>"+HTMLDisplay.getStarChar(store.getStar_store()));
						/*
						htmlBuff.append("<div id=\"demo"+store.getId_store()+"\" class=\"demo\">");
						//htmlBuff.append("网站推荐指数:");
						htmlBuff.append("</div>");
						htmlBuff.append("<script type=\"text/javascript\">");
						htmlBuff.append("$('#demo"+store.getId_store()+"').rater('star', {maxvalue:10, style: 'basic',curvalue:"+store.getStar_store()+"});");
						htmlBuff.append("</script>");//*/
						
							
						
						searcherBean.setId(store.getId_store()+"");
						searcherBean.setContent(contentBuff.toString());
						searcherBean.setIntroduction(introduction);
						searcherBean.setImage(store.getImage_store());
						searcherBean.setDate("");
						searcherBean.setUrl("../business/store.action?id="+store.getId_store()+"&from=REMOTE");
						searcherBean.setTitle(store.getName_store());
						searcherBean.setHtmlcode(htmlBuff.toString());
						searcherBean.setKind("STORE");
						
						
						
						
						indexSearcherBean(writer,searcherBean);
					}
					storeResultSet.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (CorruptIndexException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}//*/
	}

} 

